package tools;

import java.util.*;

public class Tree<T> {

	public Node<T> root;
	
	public Tree(T rootValue) {
		this.root = new Node<T>(rootValue);
	}
	
	public void add2Level(T value, int level) {
		for (Node<T> n : getLevel(level)) {
			n.addChild(new Node<T>(value));
		}
	}
	
	public List<Node<T>> getLevel(int level) {
		List<Node<T>> result = new ArrayList<Node<T>>();
		getLevel(root, level, result);
		return result;
	}
	
	public void getLevel(Node<T> node, int level, List<Node<T>> result) {
		if (node.level == level) {
			result.add(node);
		} else if (node.level < level && !node.children.isEmpty()) {
			for (Node<T> n : node.children) {
				getLevel(n, level, result);
			}			
		}
		
	}
	
	public List<LinkedList<T>> getAllPath() {
		List<LinkedList<T>> paths = new ArrayList<LinkedList<T>>();
		getAllPath(root, paths);
		return paths;
	}
	
	private void getAllPath(Node<T> node, List<LinkedList<T>> paths) {
		if (node.children.isEmpty()) {
			LinkedList<T> path = new LinkedList<T>();
			Node<T> itr = node;
			while (itr != null) {
				path.addFirst(itr.value);
				itr = itr.parent;
			}
			paths.add(path);
		} else {
			for (Node<T> n : node.children) {
				getAllPath(n, paths);
			}
		}
	}
	
	public void showTree() {
		showNode(root);
	}
	
	private void showNode(Node<T> node) {
		if(node.children.isEmpty()) {
			String msg = "";
			Node<T> itr = node;
			while (itr != null) {
				msg += itr + ", ";
				itr = itr.parent;
			}
			System.out.println(msg);
		} else {
			for (Node<T> n : node.children) {
				showNode(n);
			}
		}
	}

}
